package DianShang_2024.ds_06.extract



import org.apache.hudi.DataSourceWriteOptions.{PARTITIONPATH_FIELD, PRECOMBINE_FIELD, RECORDKEY_FIELD}
import org.apache.hudi.QuickstartUtils.getQuickstartWriteConfigs
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.{col, date_format, lit, max}

import java.util.Properties

object extract02 {
  def main(args: Array[String]): Unit = {
    /*
          抽取shtd_store库中sku_info的增量数据进入Hudi的ods_ds_hudi库中表sku_info。根据ods_ds_hudi.sku_info表中create_time作为增量字
          段，只将新增的数据抽入，字段名称、类型不变，同时添加分区，分区字段为etl_date，类型为String，且值为当前比赛日的前一天日期（分区字
          段格式为yyyyMMdd）。id作为primaryKey，operate_time作为preCombineField。使用spark-shell执行show partitions
           ods_ds_hudi.sku_info命令
     */

    //  准备spark集成hudi的环境 strict:严格的
    val spark=SparkSession.builder()
      .master("local[*]")
      .appName("数据抽取第二题")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    //  准备连接mysql的配置
    val connect=new Properties()
    connect.setProperty("user","root")
    connect.setProperty("password","123456")
    connect.setProperty("driver","com.mysql.jdbc.Driver")

    //  定义sku_info在hdfs上面的路径
    val sku_info_path="hdfs://192.168.40.110:9000/user/hive/warehouse/ods_ds_hudi.db/sku_info"

    //  拿到hudi表里面最大的时间值
    val max_time=spark.read.format("hudi")
      .load(sku_info_path)
      .agg(max(col("create_time")))
      .first()
      .get(0)
      .toString

    //  打印最大的时间值
    println("最大的世间值",max_time)

    //    根据条件抽取数据
    //  下面替换create_time是为了转换时间类型的格式，格式化。否则传进去的数据啊会有问题
    spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_store?useSSL=false","sku_info",connect)
      .withColumn("etl_date",lit("20240101"))
      .where(
        col("create_time")    > lit(max_time).cast("timestamp")
      )
      .withColumn(
        "create_time",
        date_format(col("create_time"),"yyyy-MM-dd HH:mm:ss")
      )
      .write.mode("append").format("hudi")
      .options(getQuickstartWriteConfigs)
      .option(PRECOMBINE_FIELD.key(),"create_time")
      .option(RECORDKEY_FIELD.key(),"id")
      .option(PARTITIONPATH_FIELD.key(),"etl_date")
      .option("hoodie.table.name","sku_info")
      .save(sku_info_path)


    //  关闭spark的环境
    spark.close()

  }

}
